package chapter07;

import java.util.ArrayList;
import java.util.HashSet;

public class Java09_Collection_Set_02 {
    public static void main(String[] args) {
        // TODO 集合 - Set重复数据处理
        // HashSet底层数据为：数组 + 链表

        HashSet set = new HashSet();

        User9 user1 = new User9();
        user1.id = 1001;
        user1.name = "zhangsan";
        System.out.println(user1.hashCode());   // 990368553

        User9 user2 = new User9();
        user2.id = 1001;
        user2.name = "zhangsan";
        System.out.println(user2.hashCode());   // 1096979270

        User9 user3 = new User9();
        user3.id = 1002;
        user3.name = "lisi";

        set.add(user1);
        set.add(user2);
        set.add(user3);

        System.out.println(set);    // [User[1001,zhangsan], User[1001,zhangsan], User[1002,lisi]]

        // 为什么数据会重复呢？
        // HashSet中认为user1与user2的内存地址并不相同属于不同的对象

    }
}
class User9 {
    public int id;
    public String name;

    @Override
    public String toString() {
        return "User["+id+","+name+"]";
    }

    @Override
    // 类似于内存地址
    public int hashCode() {
        return id;
    }

    @Override
    // 判断两个对象的属性是否相同
    public boolean equals(Object obj) {
        if (obj instanceof User9) {
            User9 otherUser = (User9)obj;
            if (otherUser.id == this.id) {
                if (otherUser.name.equals(this.name)) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    }
}